package com.yc.supermarket.web.controller;

import com.yc.supermarket.entity.Admin;
import com.yc.supermarket.entity.ShoppingCart;
import com.yc.supermarket.service.IAdminBiz;
import com.yc.supermarket.service.ShoppingCartService;
import com.yc.supermarket.service.impl.ShoppingCartServiceImpl;
import com.yc.supermarket.vo.ResultVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
@WebServlet("/cart")
public class ShoppingCartController extends BaseController {

    private ShoppingCartService service = new ShoppingCartServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String op=req.getParameter("op");
        System.out.println("the op:");
        if("finds".equals(op)) {
            doFinds(req, resp);
        } else if ("delete".equals(op)) {
            doDelete(req, resp);
        }else if ("updata".equals(op)) {
            doUpdata(req, resp);
        } else {
            resp.getWriter().print("weige:no such Method......");
        }
    }

    protected void doFinds(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, Object> map = parseRequest(req);
        Map<String, Object> m = service.finds(map);
        System.out.println(service.finds(map));
        printToJson(resp, m);
    }

    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("the=hello");
        ShoppingCart shoppingCart = parseRequest(req, ShoppingCart.class);
        ResultVO vo = service.delete(shoppingCart);
        printToJson(resp, vo);
    }

    protected void doUpdata(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ShoppingCart shoppingCart = parseRequest(req, ShoppingCart.class);
        int len=Integer.parseInt(req.getParameter("lengths"));
        System.out.println("len:"+len);
        int k=0;
        for(int i=0;i<len;i++){
            ShoppingCart shoppingCart1 =new ShoppingCart();
            int cartid=Integer.parseInt(req.getParameter("goods["+i+"][cardId]"));
            shoppingCart1.setCardId(cartid);
            int sum=Integer.parseInt(req.getParameter("goods["+i+"][quantity]"));
            shoppingCart1.setQuantity(sum);
             k=service.update(shoppingCart1);
        }
        if(k==0){
            System.out.println("更新失败");
            printToJson(resp, 0);
        }else {
            System.out.println("更新成功");
            printToJson(resp, 1);
        }
    }
    }
